package com.zxing.activity;

import java.io.IOException;
import java.util.Vector;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.UrlQuerySanitizer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.boyuan.huijiaoyu.HomeContactDeail1Activity;
import com.boyuan.huijiaoyu.HomeContactDeail2Activity;
import com.boyuan.huijiaoyu.R;
import com.boyuan.huijiaoyu.ScanResultActivity;
import com.boyuan.huijiaoyu.SettingPolicyActivity;
import com.example.contactfragment.ContactService;
import com.example.contactfragment.HomeContactOrgActivity;
import com.example.newfragment.DetailPerson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.magicsoft.app.helper.StringUtils;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.zxing.camera.CameraManager;
import com.zxing.decoding.CaptureActivityHandler;
import com.zxing.decoding.InactivityTimer;
import com.zxing.view.ViewfinderView;

/**
 * Initial the camera
 * 
 * @author Ryan.Tang
 */
public class CaptureActivity extends Activity implements Callback {

	private final static int INTENT_ACTION_OPEN_SCAN_RESULT = 6; // 弹出扫描结果
	public final static int INTENT_ACTION_OPEN_DOOR = 8;// 开门门禁
	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.80f;
	private boolean vibrate;
	private Button cancelScanButton;
	private Button btn_flashlight;// 闪光灯
	private Camera camera;
	private ContactService contactService;
	
	private DetailPerson homeContactDetailEntity;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera);
		// ViewUtil.addTopView(getApplicationContext(), this,
		// R.string.scan_card);
		CameraManager.init(getApplication());

		btn_flashlight = (Button) findViewById(R.id.btn_flashlight);
		btn_flashlight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (CameraManager.get().openOrOffLight()) {
					btn_flashlight.setSelected(true);
				} else {
					btn_flashlight.setSelected(false);
				}
//				camera = CameraManager.get().getCamera();
//
//				if (camera != null) {
//
//					CameraManager.get().startPreview();
//					Parameters parameters = camera.getParameters();
//
//					if (Parameters.FLASH_MODE_OFF.equals(parameters
//							.getFlashMode())) {
//						turnOn(parameters);
//					} else if (Parameters.FLASH_MODE_TORCH.equals(parameters
//							.getFlashMode())) {
//						turnOff(parameters);
//					}
//				}

			}
		});

		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		viewfinderView.getSlideBottom(new GetOneRecordListener<Integer>() {

			@Override
			public void onFinish(Integer data) {

//				if (data > 0) {
//					RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) btn_flashlight
//							.getLayoutParams();
//					params.setMargins(LayoutParams.WRAP_CONTENT, data + 40,
//							LayoutParams.WRAP_CONTENT,
//							LayoutParams.WRAP_CONTENT);//
//
//					btn_flashlight.setLayoutParams(params);
//
//				}
			}

			@Override
			public void onFailed(String Message) {
				// TODO Auto-generated method stub

			}
		});
		cancelScanButton = (Button) this.findViewById(R.id.btn_cancel_scan);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	private void turnOn(Parameters parameters) {
		if (camera != null) {

			parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
			camera.setParameters(parameters);
			// btn_flashlight.setText("关闭闪光灯");
			btn_flashlight.setSelected(true);
		}
	}

	private void turnOff(Parameters parameters) {
		if (camera != null) {

			parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.setParameters(parameters);
			// btn_flashlight.setText("开启闪光灯");
			btn_flashlight.setSelected(false);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;

		// quit the scan view
		cancelScanButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 增加取消返回结果

				setResult(RESULT_CANCELED);
				CaptureActivity.this.finish();
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		CameraManager.get().closeDriver();
		super.onDestroy();
	}

	/**
	 * Handler scan result
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = result.getText();
		// FIXME
		if (resultString.equals("")) {
			Toast.makeText(CaptureActivity.this, "Scan failed!",
					Toast.LENGTH_SHORT).show();
		} else {

			handleScan(resultString);
			// Intent resultIntent = new Intent();
			// Bundle bundle = new Bundle();
			// bundle.putString("result", resultString);
			// resultIntent.putExtras(bundle);
			// this.setResult(RESULT_OK, resultIntent);
		}
		// CaptureActivity.this.finish();
	}

	/**
	 * 查看第三方扫描二维码的页面
	 */
	private void openProductListWebsite(final String addr,
			UrlQuerySanitizer sanitizer) {

		if (sanitizer.getValue("sid") != null
				&& sanitizer.getValue("bid") != null) {
			String sid = sanitizer.getValue("sid");
			String bid = sanitizer.getValue("bid");

		} else {
			unrecognizedScanResult(addr);
		}

	}

	// 跳转到门禁
//	private void openDoorScanResult(String qrcode) {
//		Intent intent = new Intent(CaptureActivity.this,
//				ScanResultDoorOpenActivity.class);
//		intent.putExtra("qrcode", qrcode);
//		startActivityForResult(intent, INTENT_ACTION_OPEN_DOOR);
//		finish();
//	}

	// 显示扫描的结果
	private void unrecognizedScanResult(String result) {
		Log.e("CaptureActivity", "result ="+result);
		Intent intent = null;
		if (StringUtils.isURL(result)) {
			if (result.toLowerCase().contains("http:") == false
					&& result.toLowerCase().contains("https:") == false
					&& result.toLowerCase().contains("ftp:") == false
					&& result.toLowerCase().contains("mms:") == false
					&& result.toLowerCase().contains("rtsp:") == false) {
				result = "http://" + result;
			}else if(result.contains("http://fir.im/t31a")&& result.contains("action=contact")){
				dealwithResult(result);
				return;
			}
			intent = new Intent(CaptureActivity.this,
					SettingPolicyActivity.class);

			intent.putExtra("addr", result);
			intent.putExtra("title", "扫描结果");
			intent.putExtra("isshop", "true");

		} else {
			intent = new Intent(CaptureActivity.this, ScanResultActivity.class);
			intent.putExtra("result", result);
			return;
		}
		startActivityForResult(intent, INTENT_ACTION_OPEN_SCAN_RESULT);
	}
	
	private void dealwithResult(String result) {
		String a = "id";
		int indexOf = result.indexOf(a);
		String substring = "";
		int indexOf2 = result.indexOf("&", indexOf);
		if (indexOf2 == -1) {
			substring = result.substring(indexOf + a.length() + 1);
		} else {
			substring = result.substring(indexOf + a.length() + 1, indexOf2);
		}
		getContactDetail(substring);
	}

	private void getContactDetail(final String uid) {

		
		if (contactService == null) {
			contactService = new ContactService(getApplicationContext());
		}
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		final String yonghuID = sp.getString("id", "");

		contactService.getContactdetail(yonghuID, uid,
				new GetOneRecordListener<DetailPerson>() {

					@Override
					public void onFinish(DetailPerson data) {
						// TODO Auto-generated method stub
						homeContactDetailEntity = data;
						if(homeContactDetailEntity.getIs_common().equals("1")||homeContactDetailEntity.getIs_favorite().equals("1")){
							Intent intent = new Intent(CaptureActivity.this,HomeContactDeail2Activity.class);
							intent.putExtra("uid", homeContactDetailEntity.getUid());
							startActivity(intent);
							finish();
						}else{
							Intent intent = new Intent(CaptureActivity.this,HomeContactDeail1Activity.class);
							intent.putExtra("realname", homeContactDetailEntity.getRealname());
							intent.putExtra("sex", homeContactDetailEntity.getSex());
							intent.putExtra("account_mobile", homeContactDetailEntity.getAccount_mobile());
							intent.putExtra("yonghuID", yonghuID);
							intent.putExtra("uid", uid);
							startActivity(intent);
							finish();
						}

					}

					@Override
					public void onFailed(String Message) {
						// TODO Auto-generated method stub
						ToastHelper.showMsg(CaptureActivity.this,
								Message, false);
					}
				});
	}
	
	/**
	 * 处理扫描结果
	 * 
	 * @param result
	 */
	private void handleScan(String result) {
		Log.e("CaptureActivity", "handleScan result ="+result);
		UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
		sanitizer.setAllowUnregisteredParamaters(true);
		sanitizer.parseUrl(result);

		if (result.contains("kakatool.com") == false) {
			// 非kakatool二维码规范
			if (result.contains("open.meishow.com/magic.soft") == true) {
				// 魅秀
				openProductListWebsite(result, sanitizer);
			} else if (result.contains("www.360wxq.com/")) {
				// 门禁 格式规范：www.360wxq.com/QR = xx.xx.xx.xx
				if (sanitizer.getValue("QR") != null) {
					String qrcode = sanitizer.getValue("QR");
//					openDoorScanResult(qrcode);
				} else {
					unrecognizedScanResult(result);
				}

			} else if (result.contains("http://kkt.me/dr/")) {
				// 门禁 新的格式规范：http://kkt.me/dr/CSH000001
//				String qrcode = result.replace("http://kkt.me/dr/", "");
//				openDoorScanResult(qrcode);
			} else {
				// 显示扫描信息
				unrecognizedScanResult(result);
			}

			return;
		}

		if (sanitizer.getParameterList().size() == 1
				&& sanitizer.getValue("B") != null) {
			// 扫描商户二维码 加会员
			String bid = sanitizer.getValue("B");
			if (isNumeric(bid)) {

			} else {
				ToastHelper.showMsg(CaptureActivity.this, "二维码识别错误", false);
				unrecognizedScanResult(result);
			}

		} else if (sanitizer.getParameterList().size() == 2
				&& sanitizer.getValue("B") != null
				&& sanitizer.getValue("C") != null) {
			// 扫描C端商户二维码 推荐加会员
			String bid = sanitizer.getValue("B");
			String cid = sanitizer.getValue("C");

			if (isNumeric(bid) && isNumeric(cid)) {

			} else {
				ToastHelper.showMsg(CaptureActivity.this, "二维码识别错误", false);
				unrecognizedScanResult(result);
			}

		} else if (sanitizer.getParameterList().size() == 1
				&& sanitizer.getValue("T") != null) {
			String tnum = sanitizer.getValue("T");

		} else if (sanitizer.getParameterList().size() == 1
				&& sanitizer.getValue("P") != null) {

		} else if (sanitizer.getParameterList().size() == 1
				&& sanitizer.getValue("Q") != null) {
			// 扫描 交易模板

		} else if (sanitizer.getParameterList().size() == 2
				&& sanitizer.getValue("F") != null
				&& sanitizer.getValue("I") != null) {
			// 扫描二维码（B端生成硬卡会员二维码） 领卡
			String bid = sanitizer.getValue("I");
			String tcid = sanitizer.getValue("F");
			if (isNumeric(bid) && isNumeric(tcid)) {
			} else {
				ToastHelper.showMsg(CaptureActivity.this, "二维码识别错误", false);
				unrecognizedScanResult(result);
			}
		} else if (sanitizer.getParameterList().size() == 2
				&& sanitizer.getValue("B") != null
				&& sanitizer.getValue("COUPON") != null) {
			// 扫描优惠券二维码 获取优惠券信息 领取优惠券
			String bid = sanitizer.getValue("B");
			String coupon = sanitizer.getValue("COUPON");
			if (StringUtils.isNotEmpty(bid) && StringUtils.isNotEmpty(coupon)) {
			}

		} else {
			unrecognizedScanResult(result);

		}

	}

	// 判断CID是否为数字
	public static boolean isNumeric(String cid) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(cid).matches();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		setResult(resultCode, data);
		finish();
		super.onActivityResult(requestCode, resultCode, data);

	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
		CameraManager.get().stopPreview();
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		@Override
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

}